package lc.com.lcpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lc.com.lcpicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import static lc.com.lcpicturebackend.constant.FileConstant.ALLOW_CONTENT_TYPES;
import static lc.com.lcpicturebackend.constant.FileConstant.ONE_M;

/**
 * 功能：url图片上传
 * 作者：lc
 * 日期：2025/1/17 2:24
 */
@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        // 校验参数
        ThrowUtils.throwIf(CharSequenceUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件url不能为空");
        try {
            // 验证 URL 格式
            new URL(fileUrl);// 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件url不合法");
        }
        // . 校验 URL 协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR, "仅支持 http 和 https 协议");
        // 3. 发送 HEAD 请求以验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 如果没有正常响应，直接返回，负责进行响应类型，大小校验
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 类型校验
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {


                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            // 校验大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    ThrowUtils.throwIf(contentLength > 2 * ONE_M,
                            ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }

        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, file);
    }
}
